var currentAypIdTu = "&aypId=" + $('#aypId').val();
console.log("2014-01-20 1 currentAypIdTu :: ", currentAypIdTu);
var baseTuUrl = $('#baseUrl').val().split("DUMMY")[0];
console.log("2014-01-20 1 baseTuUrl :: ", baseTuUrl);

//------------------------------------------------------------
var SM_GETTEACHERUTILIZATION = 'getTeacherUtilization';
var SM_GETPERIODPERSECTIONINACAD = 'getPeriodsPerSecInAcad';

function bodyOnLoad() {
	//ko.applyBindings(teacherStaffViewModel);
	console.log("document.getElementById('aypTeacherUtilizationDivID') :: ", document.getElementById('aypTeacherUtilizationDivID'));
	console.log("teacherStaffViewModel :: ", teacherStaffViewModel);
	ko.applyBindings(teacherStaffViewModel, document.getElementById('aypTeacherUtilizationDivID'));
}

//---------------------------------------------------------------------------------
function TeacherStaffViewModel() {
	var self = this;
	self.title = "Version New";
	self.windowMode = "";

	self.maxSectionTotalPeriods = ko.observable(0);
	self.SectionPeriodVOArr = ko.observableArray([]);

	self.staffArr = ko.observableArray([]);
	self.label = ko.observable('dialog test');
	/////
	self.isOpen = ko.observable(false);
	self.open = function() {
		self.isOpen(true);
	};
	self.close = function() {
		self.isOpen(false);
	};
	var item = new Object();
	self.currentContent = ko.observable();
	console.log("2014-01-29 2014-01-20  baseTuUrl , SM_GETPERIODPERSECTIONINACAD , currentAypIdTu :: ", baseTuUrl, SM_GETPERIODPERSECTIONINACAD, currentAypIdTu);
	self.getData = function() {
		console.log("2014-01-29 getData :: "); 
		var periodPerSecData = $.getJSON(baseTuUrl + SM_GETPERIODPERSECTIONINACAD + currentAypIdTu, {
			returnformat : 'json'
		}, function(allData1) {
			console.log("periodPerSecData---||---", allData1);
			var mappedContentData = jQuery.map(allData1, function(item) {
				if (self.maxSectionTotalPeriods() < item.totalperiods) {
					self.maxSectionTotalPeriods(item.totalperiods);
				};
				//self.maxSectionTotalPeriods(30);
				return new SectionPeriodVO(item);
			});
			self.SectionPeriodVOArr(mappedContentData);
			console.log("self.SectionPeriodVOArr() :: ", self.SectionPeriodVOArr());
		});

		//-----------------Loading subjectTitle JSON---------------------------------
		var tumContentJsonData = $.getJSON(baseTuUrl + SM_GETTEACHERUTILIZATION + currentAypIdTu, {
			returnformat : 'json'
		}, function(allData1) {
			showLoader(true, TYPE_LOADING);
			var constructedTeacherJson = [];
			//Modified Json
			var teacherJsonObject;
			// Modified object
			var sectionJsonObject;
			var subjectJsonObject;
			var classJsonObject;

			var sectionJsonArr;
			var subjectJsonArr;
			var classJsonArr;

			//----------Getting Unique Values-------Start--------

			var tempIdArr = [];
			for (var i = 0; i < allData1.length; i++) {
				tempIdArr.push(allData1[i].teacherId);
			}
			var uniqueIdArr = _.uniq(tempIdArr);

			//----------Getting Unique Values-------End--------

			for (var j = 0; j < uniqueIdArr.length; j++) {
				teacherJsonObject = new Object();
				// Modified object
				var teacherIdArr = [];
				var sectionIdArr = [];
				var subjectIdArr = [];
				var classIdArr = [];

				for (var k = 0; k < allData1.length; k++) {
					if (allData1[k].teacherId == uniqueIdArr[j]) {
						var tempobj = new Object();
						tempobj.teacherId = allData1[k].teacherId;
						tempobj.sectionId = allData1[k].sectionId;
						tempobj.subjectId = allData1[k].subjectId;
						tempobj.classId = allData1[k].classId;

						tempobj.title = allData1[k].title;
						tempobj.name = allData1[k].name;
						tempobj.isClassTeacher = allData1[k].isClassTeacher;
						tempobj.sectionTitle = allData1[k].sectionTitle;
						tempobj.subjectTitle = allData1[k].subjectTitle;
						tempobj.classTitle = allData1[k].classTitle;

						tempobj.emailAddress = allData1[k].emailAddress;
						tempobj.contactNumber = allData1[k].contactNumber;
						tempobj.periodPerWeek = allData1[k].periodPerWeek;
						tempobj.cePeriodPerWeek = allData1[k].cePeriodPerWeek;
						tempobj.labPeriodPerWeek = allData1[k].labPeriodPerWeek;

						teacherJsonObject.title = allData1[k].title;
						teacherJsonObject.name = allData1[k].name;

						if (allData1[k].isClassTeacher) {
							teacherJsonObject.classTitle = allData1[k].classTitle;
							teacherJsonObject.isClassTeacher = allData1[k].isClassTeacher;
						} else {
						}

						//console.log(k, " class ", allData1[k].classTitle, " name ", allData1[k].name, " isclassteacher ", allData1[k].isClassTeacher)

						teacherJsonObject.emailAddress = allData1[k].emailAddress;
						teacherJsonObject.contactNumber = allData1[k].contactNumber;
						teacherJsonObject.teacherId = allData1[k].teacherId;
						teacherJsonObject.periodPerWeek = allData1[k].periodPerWeek;
						teacherJsonObject.cePeriodPerWeek = allData1[k].cePeriodPerWeek;
						teacherJsonObject.labPeriodPerWeek = allData1[k].labPeriodPerWeek;
						sectionIdArr.push(allData1[k].sectionId)//selection ids for that group based on teacher id
						subjectIdArr.push(allData1[k].subjectId)//subjectId ids for that group based on teacher id
						classIdArr.push(allData1[k].classId)//classId ids for that group based on teacher id
						teacherIdArr.push(tempobj);
					}
				}
				var uniqueSectionIdArr = _.uniq(sectionIdArr);
				var uniqueSubjectIdArr = _.uniq(subjectIdArr);
				var uniqueClassIdArr = _.uniq(classIdArr);

				sectionJsonArr = [];

				//console.log("teacherIdArr",teacherIdArr,uniqueSectionIdArr)

				for (var s = 0; s < uniqueSectionIdArr.length; s++) {
					var subjectidGroupArr = [];
					subjectJsonArr = [];

					for ( t = 0; t < teacherIdArr.length; t++) {
						if (teacherIdArr[t].sectionId == uniqueSectionIdArr[s]) {
							classJsonArr = [];
							for (var u = 0; u < uniqueSubjectIdArr.length; u++) {
								if (teacherIdArr[t].subjectId == uniqueSubjectIdArr[u]) {
									//----------------------------------------------------
									sectionJsonObject = new Object()
									subjectJsonObject = new Object();
									for (var v = 0; v < uniqueClassIdArr.length; v++) {
										if (teacherIdArr[t].classId == uniqueClassIdArr[v]) {
											classJsonObject = new Object();
											classJsonObject.classId = teacherIdArr[t].classId
											classJsonObject.classTitle = teacherIdArr[t].classTitle
											classJsonArr.push(classJsonObject);
										}
									}
									subjectJsonObject.subjectId = teacherIdArr[t].subjectId
									subjectJsonObject.subjectTitle = teacherIdArr[t].subjectTitle

									subjectJsonObject.periodPerWeek = teacherIdArr[t].periodPerWeek
									subjectJsonObject.cePeriodPerWeek = teacherIdArr[t].cePeriodPerWeek
									subjectJsonObject.labPeriodPerWeek = teacherIdArr[t].labPeriodPerWeek

									subjectJsonObject.classDetail = classJsonArr;
									subjectJsonArr.push(subjectJsonObject);
									//----- -----------------------------------------------
									//console.log(t,"If  subjectTitle",s, subjectJsonArr )
								}
							}
							sectionJsonObject.sectionId = teacherIdArr[t].sectionId//main
							sectionJsonObject.sectionTitle = teacherIdArr[t].sectionTitle//main
						}
					}
					//console.log("-----------OUT-------------")
					sectionJsonObject.subject = subjectJsonArr//main
					sectionJsonArr.push(sectionJsonObject) //main
				}
				teacherJsonObject.section = sectionJsonArr;
				//main
				constructedTeacherJson.push(teacherJsonObject) //main
			}
			//console.log("constructedTeacherJson=======>",constructedTeacherJson)
			// var mappedContentData           = jQuery.map(allData1, function(item) {
			var mappedContentData = jQuery.map(constructedTeacherJson, function(item) {
				return new TeacherStaffVO(item)

			});
			self.staffArr(mappedContentData);

			showLoader(false);

		});

	};

	self.afterTeacherUtilizationRender = function() {
		console.log("2014-01-20 TeacherStaffViewModel afterTeacherUtilizationRender :: ");
	};

	//------------------------------For Filtering Purpose ----------------------------

	ko.utils.stringStartsWith = function(string, startsWith) {
		string = string || "";
		if (startsWith.length > string.length)
			return false;
		return string.substring(0, startsWith.length) === startsWith;
	}, self.nameSearch = ko.observable('');
	self.sectionTitleSearch = ko.observable('');
	self.subjectTitleSearch = ko.observable('');

	self.filteredRecords = ko.computed(function() {
		return ko.utils.arrayFilter(self.staffArr(), function(r) {
			return (self.nameSearch().length == 0 || ko.utils.stringStartsWith(r.name().toLowerCase(), self.nameSearch().toLowerCase()) || ko.utils.stringStartsWith(r.sectionStr().toLowerCase(), self.nameSearch()) || ko.utils.stringStartsWith(r.subjectsStr().toLowerCase(), self.nameSearch()))

		});
	});
}

function TeacherStaffVO(data) {
	var self = this;
	self.title = ko.observable();
	self.name = ko.observable();
	self.isClassTeacher = ko.observable();
	self.classTitle = ko.observable();
	self.periodPerWeek = ko.observable();
	self.cePeriodPerWeek = ko.observable();
	self.labPeriodPerWeek = ko.observable();

	self.contactNumber = ko.observable();
	self.emailAddress = ko.observable();
	self.section = ko.observableArray([]);

	self.subjectsStr = ko.computed(function() {
		var subjectCtr = "";
		//console.log("subjectCtr")
		var sec = ko.utils.arrayMap(self.section(), function(sectionItem) {
			//console.log("sectionItem---InsideLoop",sectionItem)
			var sub = ko.utils.arrayMap(sectionItem.subject(), function(subjectItem) {
				if (subjectCtr.indexOf(", " + subjectItem.subjectTitle()) == -1) {
					subjectCtr += ", " + subjectItem.subjectTitle();
					//console.log("subjectCtr---InsideLoop",subjectCtr)
				}

			});

		});

		if (subjectCtr.indexOf(", " == 0)) {
			subjectCtr = subjectCtr.substring(1, subjectCtr.length)
		}

		return subjectCtr;
	}, self);
	self.sectionStr = ko.computed(function() {
		var sectionCtr = "";
		//console.log("subjectCtr")
		var sec = ko.utils.arrayMap(self.section(), function(sectionItem) {
			//console.log("sectionItem---InsideLoop",sectionItem)

			//var sub = ko.utils.arrayMap(sectionItem.subject(), function(subjectItem) {
			if (sectionCtr.indexOf(", " + sectionItem.sectionTitle()) == -1) {
				sectionCtr += ", " + sectionItem.sectionTitle();
				//console.log("subjectCtr---InsideLoop",subjectCtr)
			}

			//});

		});

		if (sectionCtr.indexOf(", " == 0)) {
			sectionCtr = sectionCtr.substring(1, sectionCtr.length)
		}

		return sectionCtr;
	}, self);

	self.allocationStr = ko.computed(function() {
		var allocationCtr = 0;
		ctr = 0;
		var sec = ko.utils.arrayMap(self.section(), function(sectionItem) {
			//console.log("sectionItem---InsideLoop",sectionItem)
			var sub = ko.utils.arrayMap(sectionItem.subject(), function(subjectItem) {
				ctr++
				allocationCtr += Number(subjectItem.allocation());
				//console.log(self.name(),ctr,"allocationCtr---InsideLoop",subjectItem.allocation())

			});
		});
		return allocationCtr;
	}, self);

	self.cache = function() {
	};
	self.update(data)

	self.openDetailsDialog = function(item) {
		tab5ClassRoomViewModel.teacherStaffViewModel().currentContent(item);
		//var teacherDetailsDialog = $("#teachersDetails").dialog("open");
		//teacherDetailsDialog.dialog("option", "position", "center");

		console.log("2014-01-20 tab5ClassRoomViewModel.teacherStaffViewModel().isOpen() :: ", tab5ClassRoomViewModel.teacherStaffViewModel().isOpen());
		tab5ClassRoomViewModel.teacherStaffViewModel().open(true);

	}
	self.closeDetailsDialog = function() {

		$("#teachersDetails").dialog("close");

	}
}

function SectionVO(data) {
	var self = this;
	self.sectionId = ko.observable(data.sectionTitle);
	self.sectionTitle = ko.observable(data.sectionTitle);
	self.subject = ko.observableArray([]);

	var mappedSubjectData = jQuery.map(data.subject, function(item) {
		return new TUSubjectVO(item);
	});
	self.subject(mappedSubjectData);
}

function SectionPeriodVO(data) {
	var self = this;
	self.sectionId = ko.observable(data.sectionTitle);
	self.sectionTitle = ko.observable(data.sectionTitle);
	self.totalperiods = ko.observable(data.totalperiods);
}

function TUSubjectVO(data) {
	var self = this;
	self.subjectId = ko.observable(data.subjectId);
	self.subjectTitle = ko.observable(data.subjectTitle);
	self.periodPerWeek = ko.observable(data.periodPerWeek);
	self.cePeriodPerWeek = ko.observable(data.cePeriodPerWeek);
	self.labPeriodPerWeek = ko.observable(data.labPeriodPerWeek);

	self.allocation = ko.computed(function() {
		var allocationStr = Number(self.cePeriodPerWeek()) + Number(self.labPeriodPerWeek()) + Number(self.periodPerWeek());
		return allocationStr;
		//console.log("allocationStr-----------------",allocationStr)
	}, self);

	self.classDetail = ko.observableArray([]);
	console.log("error length aa 1:: ");
	var mappedClassData = jQuery.map(data.classDetail, function(item) {
		console.log("error length aa 2:: ");
		return new ClassVO(item);
	});
	self.classDetail(mappedClassData);

}

function ClassVO(data) {
	var self = this;
	self.classId = ko.observable(data.classId);
	self.classTitle = ko.observable(data.classTitle);

}

ko.utils.extend(TeacherStaffVO.prototype, {
	update : function(data) {
		this.name(data.name || "");
		this.title(data.title || "");
		this.isClassTeacher(data.isClassTeacher || "");
		this.classTitle(data.classTitle || "");
		// this.sectionTitle(data.sectionTitle || "");
		// this.subjectTitle(data.subjectTitle || "");
		this.contactNumber(data.contactNumber || "");
		this.emailAddress(data.emailAddress || "");
		this.periodPerWeek(data.periodPerWeek || "");
		this.cePeriodPerWeek(data.cePeriodPerWeek || "");
		this.labPeriodPerWeek(data.labPeriodPerWeek || "");
		//console.log("this.title==================>", this.title(), this.isClassTeacher())
		var mappedSectionData = jQuery.map(data.section, function(item) {
			return new SectionVO(item)
		});
		this.section(mappedSectionData);

	},

	acceptItem : function(item) {

	},

	//just throw away the edited item and clear the selected observables
	revertItem : function() {

	}
});

ko.utils.extend(TeacherStaffViewModel.prototype, { });

function academicYearIds(data) {
	var self = this;
	self.aypId = ko.observable(data.aypId);
	self.title = ko.observable(data.title);

}

function jsonIOError(exp) {
	console.log("jsonIOError", exp);
}

//--------------Custom Bindings--------------------

ko.bindingHandlers.triggerUpdate = {
	update : function(element, valueAccessor) {
		ko.utils.unwrapObservable(valueAccessor());
		//need to just access the observable to create the subscription
		$(element).trigger("update");
	}
}

